package net.wantongtech.xa.uploadbasicinfo.util;

import com.jcraft.jsch.*;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.util.Properties;

/**
 * sftp协议工具类
 *
 * @author MaShibo
 * 2021/1/12 0012
 */
@Slf4j
public class SFTPHelper {

    private String username = "root";

    private String host = "10.61.30.81";

    private int port = 22;

    private String password = "Huawei12#$";

    @Getter
    private Session sshSession;

    @Getter
    private ChannelSftp sftp;


    public SFTPHelper() {
    }

    public SFTPHelper(String host, int port, String username, String password) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.password = password;
    }

    public void connect() throws JSchException {
        JSch jSch = new JSch();
        sshSession = jSch.getSession(username, host, port);
        log.info("session created.");
        sshSession.setPassword(password);
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        sshSession.setConfig(sshConfig);
        sshSession.connect();
        log.info("session connected.");
        Channel channel = sshSession.openChannel("sftp");
        channel.connect();
        log.info("opening channel");
        this.sftp = ((ChannelSftp) channel);
    }

    public void disconnect() {
        if (this.sftp.isConnected()) {
            this.sftp.disconnect();
            log.info("sftp is closed already");
        }
        if (this.sshSession != null) {
            if (this.sshSession.isConnected()) {
                this.sshSession.disconnect();
                log.info("sshSession is closed already");
            }
        }
    }


}
